#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <string>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
//#include "log.hpp"

#define SIZE 1024

//Log log;

struct ThreadData{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void Usage(std::string proc){
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

void *recv_message(void *args){
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[SIZE];
    while(true){
        // 2.从server接收数据
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len_temp = sizeof(temp);

        ssize_t n = recvfrom(td->sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len_temp);
        if(n < 0){
            //log(Warning, "client recvfrom error, errno: %d, strerror: %s", errno, strerror(errno));
            continue;
        }
        buffer[n] = 0;
        // 将收到的信息打印到标准错误流2中 然后再重定向到终端设备上 模拟同一界面的发消息和收消息
        std::cerr << buffer << std::endl;
    }
}

void *send_message(void *args){
    ThreadData *td = static_cast<ThreadData *>(args);
    std::string message;
    socklen_t len = sizeof(td->server);

    std::string welcome = td->serverip;
    welcome += " coming ...";
    sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (const struct sockaddr *)&(td->server), len);

    while(true){
        std::cout << "Please Enter@ ";
        getline(std::cin, message);

        // 1.发送数据到server
        sendto(td->sockfd, message.c_str(), message.size(), 0, (const struct sockaddr *)&(td->server), len);
    }
}

int main(int argc, char *argv[]){
    // ./udpclient serverip serverport
    if (argc != 3){
        Usage(argv[0]);
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 填充服务器的网络地址结构体
    ThreadData td;
    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());
    td.serverip = serverip;

    // 创建client socket
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(td.sockfd < 0){
        //log(Fatal, "client socket create error, errno: %d, strerror: %s", errno, strerror(errno));
        exit(1);
    }
    //log(INFO, "client socket create success, sockfd: %d", td.sockfd);

    // client bind由系统完成 在首次发送数据时bind

    // 多线程执行数据的发送和接收
    pthread_t recver, sender;
    pthread_create(&recver, nullptr, recv_message, &td);
    pthread_create(&sender, nullptr, send_message, &td);

    // 线程回收
    pthread_join(recver, nullptr);
    pthread_join(sender, nullptr);

    close(td.sockfd);

    return 0;
}